<?php

namespace app\facility\controller;

use think\Db;
use think\worker\Server;


class Tcpworker1 extends Server
{
    protected $socket = 'tcp://0.0.0.0:8888';
    protected $processes = 1;

    /**
     * 收到信息
     * @param $connection
     * @param $data
     */
    public function onMessage($connection, $data)
    {
        echo $data . "\n";
        str_replace("'", "\'", $data);
        $temp_array = explode("&", $data);
        $len = sizeof($temp_array);
        if ($len == 5) {
            try {
                write_log("tcpdata:-" . $data);
                $macReg = "/^(([0-9a-fA-F]{2}:){5})([0-9a-fA-F]{2})$/";
                $mac_data = $temp_array[1];
                $insert_data = ['device_id' => $temp_array[0], 'content' => ''
                    , 'temp' => $temp_array[2], 'ticker_count' => $temp_array[3]
                    , 'upload_count' => $temp_array[4], 'add_time' => date('Y-m-d H:i:s')];
                $pid = Db::name('tcp_sniffer')->insertGetId($insert_data);

                $temp_array2 = explode(";", $mac_data);
                $now_time_num = $temp_array[3];
                $curtime = time();
                $count1 = 0;
                $count2 = 0;
                foreach ($temp_array2 as $item) {
                    if ($item != "") {
                        $count1++;
                        $temp_array3 = explode("|", $item);
                        if (sizeof($temp_array3) == 2 && preg_match($macReg, $temp_array3[0])) {
                            $t1 = $now_time_num - $temp_array3[1];
                            $t2 = $curtime - $t1;
                            $sql2 = "insert into tcp_mac_data(mac,add_time,collect_time,pid) values('" .
                                $temp_array3[0] . "','"
                                . date('Y-m-d H:i:s') . "','"
                                . date("Y-m-d H:i:s", $t2) . "','" . $pid . "');";
                            Db::execute($sql2);
                            $count2++;
                        } else {
                            write_log("error mac :" . $item, 2);
                        }
                    }
                }
                Db::execute("update tcp_sniffer set mac_count= " . $count1 . ",valid_mac_count=" . $count2
                    . " where id=" . $pid);
            } catch (\Think\Exception  $outExcep) {
                write_log("处理数据出异常了：" . $outExcep->getMessage() . "-data:" . $data, 2);
            }
        }
        $connection->send("length:" . strlen($data));
    }


    public function onConnect($connection)
    {

        echo "New Connection\n";
    }

    function mkdirs($dir, $mode = 511)
    {
        if (is_dir($dir) || @mkdir($dir, $mode)) {
            return true;
        }

        if (!mkdirs(dirname($dir), $mode)) {
            return false;
        }

        return @mkdir($dir, $mode);
    }

    function write_log($content, $type = 1)
    {
        $type_name = "info";
        if ($type == 2) {
            $type_name = "error";
        } else if ($type == 3) {
            $type_name = "other";
        }
        $t = time();
        $base_path = ROOT_PATH . 'logs/' . $type_name . '/' . date("Y-m", $t) . '/' . date("d", $t) . '/' . date("H", $t);
        mkdirs($base_path);
        $filename = $base_path . '/' . date("i") . ".log";
        $Ts = fopen($filename, "a+");
        $content = "[" . date("Y-m-d H:i:s", $t) . ']：' . $content;
        fputs($Ts, "\r\n" . $content);
        fclose($Ts);
    }

    public function onClose($connection)
    {

        echo "Connection closed\n";
    }

    /**
     * 当客户端的连接上发生错误时触发
     * @param $connection
     * @param $code
     * @param $msg
     */
    public function onError($connection, $code, $msg)
    {
        echo "error $code $msg\n";
    }

    /**
     * 每个进程启动
     * @param $worker
     */
    public function onWorkerStart($worker)
    {
        echo "onWorkerStart___\n";
    }
}
